package org.goj.practice.controller;


import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.val;
import org.goj.common.constant.ResultCode;
import org.goj.common.entity.practice.Contest;
import org.goj.common.entity.practice.ContestUser;
import org.goj.common.model.Result;
import org.goj.practice.service.ContestService;
import org.goj.practice.service.ContestUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author CK
 * @since 2021-04-20
 */
@RestController
@RequestMapping("/contest-user")
public class ContestUserController {

    @Autowired
    private ContestService contestService;

    @Autowired
    private ContestUserService contestUserService;

    /**
     * 添加用户和竞赛的关联
     *
     * @param contestId 竞赛ID
     * @param userId    用户ID
     * @param password  密码
     * @return Result<Boolean>
     * @author CK
     * @date 2021/4/22 15:26
     */
    @PostMapping("/addContestUser")
    public Result<Boolean> addContestUser(Integer contestId, Integer userId,
                                          @RequestParam(value = "password", required = false) String password) {
        QueryWrapper<Contest> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("password", "privilege").eq("contest_id", contestId);
        Contest contest = contestService.getOne(queryWrapper);
        Assert.notNull(contest, "此竞赛不存在");
        if (contest.getPrivilege() == 1) {
            Assert.isTrue(contest.getPassword().equals(password), "密码验证失败");
        }
        int flag = contestUserService.addContestUser(contestId, userId);
        Assert.isTrue(flag > 0, "参与竞赛失败");
        return Result.succeed("参与竞赛成功", true);
    }

    /**
     * 验证用户能否进入此比赛
     *
     * @param contestId 竞赛ID
     * @param userId    用户ID
     * @return Result<Boolean>
     * @author CK
     * @date 2021/4/22 17:02
     */
    @GetMapping("/validateContestUser")
    public Result<Boolean> validateContestUser(Integer contestId, Integer userId) {
        QueryWrapper<ContestUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("contest_id", contestId).eq("user_id", userId);
        ContestUser contestUser = contestUserService.getOne(queryWrapper);
        if (ObjectUtil.isNull(contestUser)) {
            return Result.failed(ResultCode.USER_ERROR_A0404.getCode(), ResultCode.USER_ERROR_A0404.getMessage(), false);
        }
        return Result.succeed("验证成功", true);
    }

}

